import { useRequest } from 'ahooks';
import { Button, Descriptions, Empty, Form, Input, Spin, Typography } from 'antd';
import moment from 'moment';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';

import { PrismCode } from '@/components/SourceCode';
import { VulnerableProps } from '@/components/VulnerableTemplate/type';
import sqliCode from '@/pages/vulnerable/code/sqli';

import { queryUserById } from '../../service';

const { Title } = Typography;

const codeProps: PrismCode = {
  language: 'tsx',
  code: sqliCode.number,
};

const Vulnerable: React.FC = () => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<any[]>([]);
  const { t } = useTranslation();

  // 获取用户信息
  const { run, loading } = useRequest(
    async () => {
      const params = form.getFieldsValue();
      await queryUserById(params).then(res => setDataSource(res));
    },
    { manual: true },
  );

  return (
    <>
      <Title italic level={4}>
        {t('sqli.number.title')}
      </Title>
      <Form form={form}>
        <Input.Group compact>
          <Form.Item name="id" noStyle>
            <Input placeholder={t('userid') as string} style={{ width: 200, marginBottom: 20 }} />
          </Form.Item>
          <Button onClick={run}>{t('confirm')}</Button>
        </Input.Group>
      </Form>
      <Title italic level={4}>
        {t('userinfo')}
      </Title>
      <Spin spinning={loading}>
        {dataSource.length === 0 && (
          <Empty
            style={{ color: 'var(--empty-font)' }}
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={t('empty')}
          />
        )}
        {dataSource.map((m, idx) => (
          <Descriptions column={{ xxl: 4, xl: 4, lg: 2, md: 2, sm: 2, xs: 1 }} key={idx}>
            <Descriptions.Item label="id">{m.id}</Descriptions.Item>
            <Descriptions.Item label="username">{m.username}</Descriptions.Item>
            <Descriptions.Item label="create_time">
              {moment(m.create_time).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
            <Descriptions.Item label="update_time">
              {moment(m.update_time).format('YYYY-MM-DD HH:mm:ss')}
            </Descriptions.Item>
          </Descriptions>
        ))}
      </Spin>
    </>
  );
};

const SqliNumber: VulnerableProps = {
  vulnerable: <Vulnerable />,
  codeProps,
  causesSolutions: {
    type: 'sqli',
    hasCompare: true,
    solutions: 5,
  },
};

export default SqliNumber;
